<template>
  <div>
    <a-space>
      <a-select style="width: 150px" v-model="alarmId">
        <a-select-option v-for="item in events" :key="item.identifier">
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-input-number v-model="mindex"></a-input-number>
      <a-button @click="refreshAlarms()">刷新告警</a-button>
      <a-button :disabled="alarmId === ''" @click="forceAlarm('BEGIN')">模拟告警</a-button>
      <a-button :disabled="alarmId === ''" @click="forceAlarm('END')">模拟消除</a-button>
    </a-space>
    <br />
    Cache:
    <alarm-table :alarms="alarmsCache"></alarm-table>
    DB:
    <alarm-table :alarms="alarmsDB"></alarm-table>
  </div>
</template>
<script>
import {
  forceAalarm,
  getAlarmFromCache,
  getAlarmFromDB,
} from "@/services/alarmAPI";
import AlarmTable from "@/components/alarm/alarmTable";

export default {
  components: {
    AlarmTable,
  },
  props: ["thing"],
  data() {
    return {
      events: {},
      alarmId: "",
      mindex: 0,
      alarmsCache: [],
      alarmsDB: [],
    };
  },
  watch: {
    thing(newv) {
      if (newv) {
        let mid = newv.model_id;
        this.refresh(mid);
      }
    },
  },
  created() {
    if (this.thing) {
      let mid = this?.thing?.model_id;
      this.refresh(mid);
    }
  },
  methods: {
    refreshAlarms() {
      let self = this;
      getAlarmFromCache(this.thing.uid).then((res) => {
        if (res && res.data && res.data.result) {
          self.alarmsCache = res.data.result;
        } else {
          self.alarmsCache = [];
        }
      });
      getAlarmFromDB(this.thing.uid).then((res) => {
        if (res && res.data && res.data.result) {
          self.alarmsDB = res.data.result;
        } else {
          self.alarmsDB = [];
        }
      });
      this.refresh();
    },
    refresh(mid) {
      if (!mid) {
        mid = this.thing?.model_id;
      }
      if (mid) {
        let self = this;
        this.$store.dispatch("tmodel/refreshTModelByID", mid).then((model) => {
          if (model) {
            self.events = model?.body?.events;
            console.log("*********", self.events);
          }
        });
      }
    },
    forceAlarm(flag) {
      if (this.alarmId) {
        forceAalarm(this.thing.uid, this.alarmId, this.mindex, flag);
        let self = this;
        setTimeout(() => {
          self.refreshAlarms();
        }, 500);
      }
    },
  },
};
</script>